import { Device } from 'react-native-ble-plx'
import BleConstants, { DeviceState, ResponseCode } from '@CONSTANTS/BleConstants'
import DeviceInfo from 'react-native-device-info'
import MD5 from '@UTILS/Md5'
import { base64 } from '@pier88health/p8h-common'
import Storage, { StorageKey } from '@UTILS/Storage'

export default class BluUtils {
  static isNewDevice = (name: string) => {
    console.log('BluUtilsBluUtils')
    console.log('BluUtilsBluUtils')
    console.log('BluUtilsBluUtils')
    if (!name) return false
    const tokens = name.split(' ')
    return tokens[2] === '1'
  }

  static isDeviceNear(device: Device) {
    return !!device?.rssi && device?.rssi > BleConstants.NEAR_RSSI_LIMIT
  }

  static getUuidData = async () => {
    // const userId = '6bb58e85-1f9a-4088-b310-2df793a64788'
    const userId = await Storage.get(StorageKey.userId)
    const udId = DeviceInfo.getDeviceId() + userId
    console.log('userId11', userId)

    const hashedUDID = MD5.hex_md5(udId)
    return base64.encode(`UDID ${hashedUDID}\n`)
  }

  static getTimeData = () => {
    return base64.encode(`time ${parseInt(String(Date.now() / 1000), 10)}\n`)
  }

  static getPasswordData = async () => {
    // const userId = '6bb58e85-1f9a-4088-b310-2df793a64788'
    const userId = await Storage.get(StorageKey.userId)
    console.log('userId', userId)
    const hashedUDID = MD5.hex_md5(userId)
    return base64.encode(`pwd ${hashedUDID}\r`)
  }

  static toDeviceState = (int: number) => {
    switch (int) {
      case 1:
        return DeviceState.Idle
      case 2:
        return DeviceState.InitTreatment
      case 3:
        return DeviceState.Treatment
      case 4:
        return DeviceState.Error
      case 5:
        return DeviceState.Pause
      case 6:
        return DeviceState.Shutdown
      default: {
        return DeviceState.Unknown
      }
    }
  }

  static toDeviceStatusFlags = () => {
    // TODO
  }

  static toResponseCode = (int: number) => {
    switch (int) {
      case 0x100:
        return ResponseCode.IllegalParameters
      case 0x102:
        return ResponseCode.DeviceIsNotAuthenticated
      case 0x200:
        return ResponseCode.TreatmentIsAlreadyActive
      case 0x202:
        return ResponseCode.TreatmentIsNotActive
      case 0x207:
        return ResponseCode.TreatmentIsAlreadyPaused
      case 0x208:
        return ResponseCode.ExceededMaximumPausesInTreatment
      case 0x209:
        return ResponseCode.TreatmentIsInitializing
      case 0x20B:
        return ResponseCode.TreatmentIsBlocked
      case 0x20C:
        return ResponseCode.NoMoreTreatmentsLeft
      case 0x600:
        return ResponseCode.RequestForPassword
      case 0x602:
        return ResponseCode.ExceedMaximumPasswordTrials
      case 0x603:
        return ResponseCode.InvalidPassword
      default: {
        return ResponseCode.Unknown
      }
    }
  }
}
